# clear_logs.py
"""
日志清理工具：自动保留最新的 N 个日志文件
支持区分“手动执行”和“自动执行”
"""

from datetime import datetime
import argparse

from config.settings import LOGS_DIR, LOG_PATTERN, DEFAULT_LOG_KEEP_COUNT


def log_cleanup_history(deleted_count: int, keep_count: int, source: str = "manual"):
    """记录清理历史，区分手动和自动"""
    history_log = LOGS_DIR / "cleanup_history.log"
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    source_desc = "自动清理" if source == "auto" else "手动清理"

    log_msg = f"[{timestamp}] {source_desc}：删除 {deleted_count} 个文件，保留最新 {keep_count} 个"
    print(f"📝 {log_msg}")  # 控制台也输出

    with open(history_log, 'a', encoding='utf-8') as f:
        f.write(log_msg + "\n")


def cleanup_old_logs(keep_count: int = 20, force: bool = False, source: str = "manual"):
    """清理旧日志"""
    if keep_count < 0:
        print("❌ 保留数量不能为负数")
        return

    if not LOGS_DIR.exists():
        print(f"❌ 日志目录不存在: {LOGS_DIR}")
        return

    log_files = list(LOGS_DIR.glob(LOG_PATTERN))
    if len(log_files) <= keep_count:
        print(f"✅ 日志数量 ({len(log_files)}) ≤ 保留数量 ({keep_count})，无需删除。")
        return

    sorted_logs = sorted(log_files, key=lambda f: f.stat().st_ctime)
    files_to_delete = sorted_logs[:-keep_count]

    print(f"🔍 找到 {len(log_files)} 个日志文件。")
    print(f"🗑️ 需删除最旧的 {len(files_to_delete)} 个文件，保留最新的 {keep_count} 个。")

    if not force:
        confirm = input(f"\n⚠️ 确认删除这 {len(files_to_delete)} 个文件？(y/N): ")
        if confirm.lower() not in ['y', 'yes']:
            print("✅ 取消操作，未删除任何文件。")
            return

    deleted_count = 0
    for file in files_to_delete:
        try:
            file.unlink()
            print(f"✅ 已删除: {file.name}")
            deleted_count += 1
        except Exception as e:
            print(f"❌ 删除失败 {file.name}: {e}")

    # 🟢 记录来源
    log_cleanup_history(deleted_count, keep_count, source=source)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="清理旧日志，保留最新的 N 个")
    parser.add_argument('--keep', '-k', type=int, default=DEFAULT_LOG_KEEP_COUNT, help='保留的最新日志数量')
    parser.add_argument('--force', '-f', action='store_true', help='强制执行，不提示确认')

    # 🔥 新增：指定来源
    parser.add_argument(
        '--source',
        choices=['manual', 'auto'],
        default='manual',
        help='执行来源：manual=手动，auto=自动（用于任务计划）'
    )

    args = parser.parse_args()
    cleanup_old_logs(keep_count=args.keep, force=args.force, source=args.source)